﻿using Quartz;
using System;
using System.Net;
using System.Text;
using Ttifa.Infrastructure.Utils;
using Ttifa.Log;

namespace Ttifa.CronScheduler.Quartz
{
    public class ApiJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                var api = context.JobDetail.JobDataMap["Api"].ToString();
                var param = context.JobDetail.JobDataMap["Param"]?.ToString();
                if (string.IsNullOrEmpty(param)) param = "";
                var apiurl = ConfigManager.GetSetting("apihost") + api;

                WebRequest request = WebRequest.Create(apiurl);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                byte[] paramsArr = Encoding.UTF8.GetBytes(param);
                request.ContentLength = paramsArr.Length;
                request.GetRequestStream().Write(paramsArr, 0, paramsArr.Length);

                WebResponse response = request.GetResponse();
                var resp = string.Empty;
                using (var stream = response.GetResponseStream())
                {
                    var streamReader = new System.IO.StreamReader(stream, Encoding.UTF8);
                    resp = streamReader.ReadToEnd().Replace("\n", "");
                }

                LogFactory.GetLogger().Info($"{api}:{resp}");
            }
            catch (Exception ex)
            {
                LogFactory.GetLogger().Error("请求失败", ex);
            }
        }
    }
}
